package com.esaheki.flashcards.uiSupport;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Random;

import com.esaheki.flashcards.classes.*;
import com.esaheki.flashcards.dao.*;

/**
 * Roulette é a classe que implementa a roleta que sorteia as cartas de acordo
 * o score. A probabilidade de uma carta ser escolhida é o inverso do score + 0.1.
 * 
 * @author      Elton Saheki Horikoshi <esaheki@gmail.com>
 */
public class Roulette {
	
	private Object obj;
	
	public Roulette () {
		
	}
	
	public Roulette (Object obj) {
    	this.obj = obj;
	}
	
	public Card getCard() {
		ArrayList<Card> cardlist = new ArrayList<Card>();
		try {
			CardDAO cDao = new CardDAO();

			if (obj instanceof Category) {
				cardlist = cDao.getCardListByCategory((Category) obj);
			}
			else if (obj instanceof User) {
				cardlist = cDao.getCardListByUser((User) obj);
			}
			else if (obj instanceof ArrayList<?>) {
				cardlist = cDao.getAllCardList();
			}
			else if (obj == null) {
				cardlist = cDao.getAllCardList();
			}
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			return null;
		}

		if (cardlist.size() <= 0) {
			return null;
		}
		Card card = new Card();
		Double sum = 0.0;
		for (Card candidate : cardlist) {
			sum += 1 - candidate.getScore() + 0.1;
		}
		Random rand = new Random();
		Double choice = sum * rand.nextDouble();

		int i = 0;
		sum = 0.0;
		while (sum < choice) {
			card = cardlist.get(i);
			sum += 1 - card.getScore() + 0.1;
			i++;
		}
		return card;
	}

}
